package org.example.servlet;

import com.google.gson.Gson;
import org.example.service.CartService;
import org.example.service.CartServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = {"/order/*"})
public class OrderServlet extends HttpServlet {
    private CartService cartService = new CartServiceImpl();
    private Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        String pathInfo = request.getPathInfo();
        int userId = 1; // 临时使用固定用户ID
        
        switch (pathInfo) {
            case "/create":
                handleCreateOrder(request, response, userId);
                break;
            case "/update":
                handleUpdateOrder(request, response);
                break;
            case "/cancel":
                handleCancelOrder(request, response);
                break;
        }
    }

    private void handleCreateOrder(HttpServletRequest request, HttpServletResponse response, int userId) 
            throws IOException {
        String orderNumber = cartService.createOrder(userId);
        
        response.setContentType("application/json");
        Map<String, String> result = new HashMap<>();
        result.put("orderNumber", orderNumber);
        response.getWriter().write(gson.toJson(result));
    }

    private void handleUpdateOrder(HttpServletRequest request, HttpServletResponse response) {
        // 这个功能可以在后续实现
        response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

    private void handleCancelOrder(HttpServletRequest request, HttpServletResponse response) {
        // 这个功能可以在后续实现
        response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
    }
} 